//专门用来存放关于用户收藏的接口
const Router = require('koa-router'); //引入路由
const collect = new Router();
const db = require('../utils/db');
const bodyparser = require('koa-bodyparser');
//写对应的接口

collect.use(bodyparser()) //调用这个中间件之后，就可以拿到前端post过来的数据

//根据id获取数据
collect.get('/:id',async ctx=>{
    const {id} = ctx.request.params;
    let searchSql = `select * from collect_class where id="${id}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql,(err,data)=>{
            if(err) throw err
            resolve(data)
        })
    })
    ctx.body = result;
})



//点击收藏
collect.post('/insert', async ctx=>{
    const data = ctx.request.body;
    let searchSql = `insert into collect_class (time,openid,content,class,releasetime,img,title) values 
    ("${data.time}","${data.openid}","${data.content}","collect","${data.releasetime}","${data.img}","${data.title}")`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })
    ctx.body = "收藏成功";
})
//查询收藏列表
collect.get('/',async ctx=>{
    let data = await new Promise((reslove,reject) => {
        return db.query(`select * from collect_class`,(err,data) => {
            if(err) console.log(err);
            reslove(data);
            })
        })
        const totalCount = data.length;
        console.log(totalCount);
        ctx.body = {
            totalCount,
            data
        }
    })

//根据openid显示收藏
collect.post('/',async ctx=>{
    const data = ctx.request.body;
    let searchSql = `select * from collect_class where openid='${data.openid}'`
    let result = await new Promise ((resolve,reject) =>{
        return db.query(searchSql,(err,data) =>{
            if(err) throw err
            resolve(data)
        })
    })
    ctx.body = result;
})

//撤销收藏
collect.post('/delete', async ctx=>{
    const data = ctx.request.body;
    let searchSql = `delete from collect_class where openid="${data.openid}" and content="${data.content}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })
    ctx.body = "撤销成功";
})

//查询是否收藏
collect.post('/select', async ctx=>{
    console.log('select')
    const data = ctx.request.body;
    let searchSql = `select * from collect_class where openid="${data.openid}" and content="${data.content}"`
    let result = await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) throw err
            resolve(data)
        })
    })
    console.log(result);
    if(JSON.stringify(result) == "[]"){
        ctx.body = 1;
    }else{
        ctx.body = 2;
    }
})

module.exports = collect;